/*
 * Copyright zhoujun 2021 Wicrenet, Inc. All rights reserved.
 */
package com.ruoyi.netty.initailizer;

import com.ruoyi.netty.handler.WebSocketServerHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 【websocket初始化配置】
 *
 * @author zhoujun
 * Created on 2021/11/24 18:10
 */
@Component
@ChannelHandler.Sharable
public class WebSocketServerInitailizer extends ChannelInitializer<SocketChannel> {
    private static final Logger                 logger = LoggerFactory.getLogger(WebSocketServerInitailizer.class);
    @Autowired
    private              WebSocketServerHandler webSocketServerHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        logger.info("websocket初始化开始...");
        ChannelPipeline pipeline = ch.pipeline();
        //web基于http协议的解码器
        pipeline.addLast(new HttpServerCodec());
        //对大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //对http message进行聚合，聚合成FullHttpRequest或FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(8192));
        //监测客户端在30秒内有没有向服务端发送心跳，三个参数分别为读/写/读写的空闲
        pipeline.addLast(new IdleStateHandler(30,30,30, TimeUnit.SECONDS));
        //websocket服务器处理对协议，用于指定给客户端连接访问的路径
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //自定义channel处理器
        pipeline.addLast(this.webSocketServerHandler);
    }
}

